package cn.iocoder.yudao.module.pay.wallet.api;

import cn.hutool.core.lang.Assert;
import cn.iocoder.yudao.module.api.pay.wallet.PayWalletApi;
import cn.iocoder.yudao.module.api.pay.wallet.dto.PayWalletAddBalanceReqDTO;
import cn.iocoder.yudao.module.api.pay.wallet.dto.PayWalletReduceBalanceReqDTO;
import cn.iocoder.yudao.module.api.pay.wallet.dto.PayWalletRespDTO;
import cn.iocoder.yudao.module.api.pay.wallet.enums.PayWalletBizTypeEnum;
import cn.iocoder.yudao.module.pay.wallet.convert.PayWalletConvert;
import cn.iocoder.yudao.module.pay.wallet.dal.dataobject.PayWalletDO;
import cn.iocoder.yudao.module.pay.wallet.service.PayWalletService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

/**
 * 钱包 API 实现类
 *
 * @author 芋道源码
 */
@Service
public class PayWalletApiImpl implements PayWalletApi {

    @Resource
    private PayWalletService payWalletService;

    @Override
    public PayWalletRespDTO getOrCreateWallet(Integer userType, Long userId) {
        PayWalletDO wallet = payWalletService.getOrCreateWallet(userId, userType);
        return PayWalletConvert.INSTANCE.convertDTO(wallet);
    }

    @Override
    public void addWalletBalance(PayWalletAddBalanceReqDTO dto) {
        // 创建或获取钱包
        PayWalletDO wallet = payWalletService.getOrCreateWallet(dto.getUserId(), dto.getUserType());
        Assert.notNull(wallet, "钱包({}/{})不存在", dto.getUserId(), dto.getUserType());
        // 增加余额
        PayWalletBizTypeEnum bizType = PayWalletBizTypeEnum.valueOf(dto.getBizType());
        payWalletService.addWalletBalance(wallet.getId(), dto.getBizId(), bizType, dto.getPrice());
    }

    @Override
    public void reduceWalletBalance(PayWalletReduceBalanceReqDTO dto) {
        // 创建或获取钱包
        PayWalletDO wallet = payWalletService.getOrCreateWallet(dto.getUserId(), dto.getUserType());
        Assert.notNull(wallet, "钱包({}/{})不存在", dto.getUserId(), dto.getUserType());
        // 减少余额
        PayWalletBizTypeEnum bizType = PayWalletBizTypeEnum.valueOf(dto.getBizType());
        payWalletService.reduceWalletBalance(wallet.getId(), dto.getBizId(), bizType, dto.getPrice());
    }

}
